import { Commit } from 'vuex'
import { getToken, removeToken } from '@/utils/auth'

export interface IUser {
    token:string|undefined
    roles:Array<string>
}

const state:IUser = {
  token: getToken(),
  roles: []
}

const mutations = {
  SET_TOKEN: (state:IUser, token:string) => {
    state.token = token
  },
  SET_ROLES: (state:IUser, roles:Array<string>) => {
    state.roles = roles
  }
}

const actions = {
  getInfo (context: { commit: Commit }) {
    return new Promise((resolve, reject) => {
      context.commit('SET_ROLES', ['user', 'admin'])
      resolve(true)
    })
  },
  // remove token
  resetToken (context: { commit: Commit }) {
    return new Promise(resolve => {
      context.commit('SET_TOKEN', '')
      context.commit('SET_ROLES', [])
      removeToken()
      resolve(true)
    })
  }
}
const getters = {
  get_roles: (state:IUser) => state.roles
}

export const user = {
  namespace: true,
  state,
  mutations,
  actions,
  getters
}
